package com.ly.hotel.service;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.ly.hotel.adaptor.NetworkUtil;
import com.ly.hotel.cloud.SocketClient;
import com.ly.hotel.common.Constants;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.common.SharedPreferencesConfig;
import com.ly.hotel.common.SysConf;
import com.ly.hotel.model.Ad;
import com.ly.hotel.model.AdDetail;
import com.ly.hotel.model.ModelBean;
import com.ly.hotel.msgevent.CloudAdShowFinishEvent;
import com.ly.hotel.msgevent.CloudSocketIdReportEvent;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.util.AppUtil;
import com.ly.hotel.util.DateUtils;
import com.ly.hotel.util.DesCryptoUtil;
import com.ly.hotel.util.FileUtils;
import com.ly.hotel.util.HttpHelper;
import com.ly.hotel.util.HttpRequestFailException;
import com.ly.hotel.util.WebInstaller;
import com.ly.hotel.view.common.AdData;
import com.ly.hotel.view.floatWindows.QRFloatWin;
import com.ly.hotel.webagent.UdpCallback;
import com.ly.hotel.webagent.UdpClient;

import org.apache.http.Header;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import java.util.Vector;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import de.greenrobot.event.EventBus;

//下面是云端接口
/*  application = tornado.web.Application([
    (r"/", monitor), 
    (r"/monitor", monitor),                                               # 信息界面
    (r"/info", info),                                                     # 信息接口
    (r"/auth", auth),                                                     # 信息界面的验证
    (r"/secnow", secnow),                                                 # 当前时间（加密版）
    (r"/now", now),                                                       # 当前时间
    (r"/version-api", apiVersion),                                        # 接口版本
    (r"/version-sys", sysVersion),                                        # 系统版本
    (r"/seckey", seckey),                                                 # 获取日志秘钥
    (r"/getsvr", getsvr),                                                 # 根据会所名查询slaver信息
    (r"/slaver", slaver),                                                 # slaver发来的心跳
    (r"/heartbeat", heartbeat),                                           # APK发来的心跳，历史原因，临时应急，APK升级然后去掉 XXXX
    (r"/seclog", seclog),                                                 # APK发来加密日志，历史原因，临时应急，APK升级后去掉 XXXX
    (r"/log", log),                                                       # APK发来普通日志，历史原因，临时应急，APK升级后去掉 XXXX
], cookie_secret = "master")
*/

/*application = tornado.web.Application([
    (r"/now", now),                                                                 # 当前时间
    (r"/log", log),                                                                 # [日志]接收非加密日志
    (r"/seclog", seclog),                                                           # [日志]接收加密日志
    (r"/heartbeat", heartbeat),                                                     # [日志]日志心跳
    (r"/seckey", seckey),                                                           # [日志]获取加密日志的秘钥             
    (r"/statis", statis),                                                           # [日志]统计信息
    (r"/cmd", cmd),                                                                 # [命令]发送命令
    (r"/cmdlist", cmdlist),                                                         # [命令]获取已连接到cmd的id列表
    (r"/cutsock", cutsock),                                                         # [命令]根据sockid切断socket连接
    (r"/cropfile/(.*)", tornado.web.StaticFileHandler, {'path':'cropfiles/'}),      # [文件]存放会所文件所在目录
    (r"/cropfile-upload", cropfileupload),                                          # [文件]上传会所文件
    (r"/cropfile-delete", cropfiledelete),                                          # [文件]删除会所文件
], cookie_secret = "slaver")
 */
public class MyCloudBackService extends Service {
	static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
	private static MyApplication app;
	public static String zipCreatTime;
	private ThisHandler handlerMsg = new ThisHandler(this);

	//private Timer heartbeat_timer = null;							// 心跳
//	private boolean check_alive_finish = false;						// 是否还继续检查云服务器是否在线
	//private Timer cloud_log_timer = null;							// 心跳
//	private boolean cloudLogin = false;								//是否已经登陆
	private boolean myCloudOnline = false;							//云端服务器是否有响应
	
	public final static int CLOUD_INIT = 1;
	public final static int CLOUD_LOGIN = 2;
	public final static int CLOUD_GET_DATA = 3;
	public static final int CLOUD_UPDATE_SPA =  4;
	
	public static String cloud_url = "";
	
	public static String httpProxy = "";
	public static int httpProxyPort = 0;
	public static boolean cloudLogsEnable = false;
	public static boolean isNeedhttpProxy = true;//会在第一次尝试链接是判断是否需要代理，如果电视不能上网，会在失败后将这个变为true
	private String secKey = "";//存放的是日志的加密串
	private int secKeyPosition[] = {1,5,9,10,13,18,19,23};
	
	public ConcurrentLinkedQueue<String> decLogsList = new ConcurrentLinkedQueue<String>();
	public ConcurrentLinkedQueue<String> logsList = new ConcurrentLinkedQueue<String>();
	
	public static String cloudLogsServerIp = "";
	public static int cloudLogsServerPort = 9001;
	
	private static ScheduledExecutorService cloudThreadPool = Executors.newScheduledThreadPool(2);
	private Map<String, Future> futures = new HashMap<String, Future>();

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		app = (MyApplication) getApplication();
		int tryTimes = 10;
		// 接收事件
		EventBus.getDefault().register(this);
		
		//等待从本地服务器获取代理服务器的IP和端口
		while(SysConf.extendConfGetValue(SysConf.SYS_CONF_HTTP_PROXY, "").equals("") && tryTimes > 0){
			Log.i("cloud", "等待获取http代理服务器配置。。。。");
			try {
				Thread.sleep(300);
				tryTimes--;
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		String proxyConf = SysConf.extendConfGetValue(SysConf.SYS_CONF_HTTP_PROXY, ""); 
		if(!proxyConf.equals("")){
			Log.i("cloud", "http代理服务器配置获取成功：" + proxyConf);
			String v[] = proxyConf.split(":");
			if(v.length == 2){
				String proxyConfIp = v[0];
				String[] w = proxyConfIp.split("\\.");
				if(w.length == 4 ){
					checkProxy(v[0],Integer.parseInt(v[1]));
				}else{
					String myHostIp = MyApplication.getHostIp();
					String x[] = myHostIp.split(":");
					httpProxy = x[0];
					httpProxyPort = 808;
					handlerMsg.sendEmptyMessageDelayed(CLOUD_INIT, 10);
					Log.i("myDebug", "代理服务器地址：" + httpProxy + ":" + httpProxyPort);
				}
				//如果使用Volley，就要初始化之
				//initVolleyUseProxy();
			}
		}else{
			Log.i("cloud", "获取http代理服务器配置失败->>" + SysConf.extendConfGetValue(SysConf.SYS_CONF_HTTP_PROXY, ""));
		}
		/*
		 * 新建一个任务检测机器是否能联网，如果能联网，就不需要通过代理了
		 */
		checkInternet();
	}
	
	private void checkProxy(String ip,int port){
		httpProxy = ip;
		httpProxyPort = port;
		new Thread(new Runnable() {
			
			@Override
			public void run() {

				if(!NetworkUtil.ping(httpProxy)){
					String myHostIp = MyApplication.getHostIp();
					String x[] = myHostIp.split(":");
					httpProxy = x[0];
					httpProxyPort = 808;
				}
				Log.i("myDebug", "代理服务器地址：" + httpProxy + ":" + httpProxyPort);
				handlerMsg.sendEmptyMessageDelayed(CLOUD_INIT, 10);
			}
		}).start();
	}
	
	private void checkInternet(){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				if(NetworkUtil.ping("www.baidu.com")){
					Log.e("cloud_alive", "机器可以直接联网...");
					isNeedhttpProxy = false;
				}
			}
		}).start();
	}
/*	private void initVolleyUseProxy(){
		if(mQueueUseProxy == null){
			OkHttpClient client = new OkHttpClient();
			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxy, httpProxyPort));
			client.setProxy(proxy);
			mQueueUseProxy = Volley.newRequestQueue(MyApplication.getContext(), new OkHttpStack(client));
			mQueueUseProxy.start();
		}
	}*/
	private void initCloudServer(){
		String url = SysConf.extendConfGetValue(SysConf.SYS_CONF_CLOUD_URL, "");
		if(!url.equals("")){
			cloud_url = url;
			checkCloudOnline();
		}
	}
	
	private void checkCloudOnline() {
		
		Log.i("cloud_heart", "checkCloudOnline.");
		final AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				
				String response = new String(arg2);
				//解析获得的ip和端口
				String server[] = response.split(" ");
				if(server.length == 2){
					Log.i("cloud_heart", "日志服务器ip:" + server[0] + "日志服务器端口:" + server[1]);
					cloudLogsServerIp = server[0];
					try {
						cloudLogsServerPort = Integer.parseInt(server[1]);
					}catch (NumberFormatException e){
						e.printStackTrace();
					}

					
					myCloudOnline = true;
					
					Future future = futures.get("alive_timer");
	                if (future != null) 
	                	future.cancel(true);
					//已经检测在线的了，如果还存在在线检测的http请求，就去掉
					SPABackService.mQueue.cancelAll("cloud_alive");
					
					//通知登录云端
					handlerMsg.sendEmptyMessageDelayed(CLOUD_LOGIN, 100);
					
					if(SysConf.extendConfGetValue(SysConf.SYS_CONF_CLOUD_LOGS_ENABLE,"1").equals("1")){
						cloudLogsEnable = true;
					}else{
						cloudLogsEnable = false;
					}
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				Log.e("cloud_alive", "云端离线:" + arg3.getMessage());
			}

		};
		
		long interval_time = 5000;
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
//					if(!check_alive_finish){
						Log.i("cloud_heart", "alive_timer running...");
						try {
	//						Thread.sleep(5000);
							//日志服务器支持分布式的。这里需要获取一下自己对应的日志服务器地址，同时也通过这个判断日志服务器是否在线
							if(MyApplication.authToCompany.equals("未获得授权") || !NetworkUtil.isConnected(getBaseContext())){
								Log.i("cloud_heart", "不能启动云服务:" + MyApplication.authToCompany + ",网络状态:" + NetworkUtil.isConnected(getBaseContext()));
							} else {
								String url = Constants.DEFAULT_CLOUD_LOGS_SERVER + "/getsvr?crop=" + MyApplication.authToCompany;
								Log.i("cloud_heart", "检测云端在线:" + url + ",代理服务器:" + MyCloudBackService.httpProxy+":"+MyCloudBackService.httpProxyPort);
								HttpHelper.myGetStringAsync(getBaseContext(), url, null, handler, isNeedhttpProxy);
							}
						} catch (Exception e) { 
							Log.e("cloud_alive", "cloud_alive:" + e.getMessage());
						}
//					}
				}
		};
		
		/*if(alive_timer == null){
			Log.i("cloud_heart", "创建alive_timer.");
			alive_timer = new Timer(true);
			alive_timer.schedule(task, 100, interval_time);	
		}*/
		
		Future<?> future = cloudThreadPool.scheduleAtFixedRate(task, 10000, interval_time, TimeUnit.MILLISECONDS);
		futures.put("alive_timer", future);
			
	}
	
	private void initHeartbeat() {
		Log.i("cloud_heart", "initHeartbeat.");
		final AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub
				Log.i("cloudheart", "云端心跳包发送完成:" + new String(arg2));
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				// TODO Auto-generated method stub
				Log.i("cloudheart", "云端心跳包发送失败."); 
			}
		};
		TimerTask task = new TimerTask() {
			@Override
			public void run() {

				if(!app.getAuthToCompany().equals("未获得授权") && myCloudOnline){
					String url = "http://" + cloudLogsServerIp + ":"+ cloudLogsServerPort  + "/heartbeat?mac=" + MyApplication.getMAC() + "&crop=";
//					url += URLEncoder.encode(app.getAuthToCompany());
					try {
						url += URLEncoder.encode(app.getAuthToCompany(), "UTF-8");
						url += "&pingms=" + app.pingMs;
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
//						Log.i("cloud_heart", "心跳包请求:" + url); 

					HttpHelper.myGetStringAsync(MyApplication.getContext(), url, null, handler, isNeedhttpProxy);
				}else{
					Log.i("cloud_heart", "未获得授权");
				}

			}
		};
		
		cloudThreadPool.scheduleAtFixedRate(task, 1000, 3 * 60 * 1000, TimeUnit.MILLISECONDS);
	}

	public static List<AdDetail> getAdInfo(String mac, int target,int type) {
		String url = cloud_url + "/api/ad-list.json?mac=" + mac 
				+ "&crop=" + app.getAuthToCompany()
				+ "&target=" + target
				+ "&type=" + type;
		Log.i("cloud_ad", "请求广告数据..." + url);
		try {
			String result = HttpHelper.myGetStringSync(null, url, isNeedhttpProxy);

			Log.d("cloud_ad", "请求广告数据.result = " + result);
			if (result == null){
				return null;
			}
			
			ModelBean b = gson.fromJson(result, ModelBean.class);
			
			if (b != null) {
				if (b.getCode().equals(-1) || b.getData() == null || b.getData().equals(""))
					return null;
				AdDetail[] sb = (AdDetail[]) b.getData(AdDetail[].class);
				if (sb != null) {
					List<AdDetail> a = Arrays.asList(sb);
					Log.i("cloud_ad", "获取云广告成功," + target + "," + type);
					return a;
				} else {
					Log.i("cloud_ad", "获取云广告失败，或者没有设置广告," + target + "," + type);
					return null;
				}
			}
			Log.i("cloud_ad", "获取云广告失败，或者没有设置广告,");
			return null;
		} catch (Throwable e) {
			Log.e("cloud_ad", "广告数据获取失败:" + e.getMessage());
			e.printStackTrace();

		}
		return null;
	}
	
	private void initAd() {
		if (MyApplication.adEnable && myCloudOnline) {
			String enable = SysConf.extendConfGetValue(SysConf.SYS_CONF_AD_ENABLE, "");
			Log.i("cloud_ad", "云广告同步，状态:" + enable);
			if (enable.equals("1")) {
				new Thread() {
					@Override
					public void run() {
						Log.i("cloud_ad", "云广告进程启动..");
						Looper.prepare();//这个不能去掉，去掉了，801就不能播放电影了
						//电影广告
						Ad adVod = new Ad();
						adVod.setType(Ad.VOD);
						List<AdDetail> vod_adsList = new Vector<AdDetail>();
						vod_adsList.clear();
						
						List<AdDetail> vod_adsPic = getAdInfo(MyApplication.getMAC(), Ad.VOD, 1);
						if(vod_adsPic != null){
							vod_adsList.addAll(vod_adsPic);
						}
						List<AdDetail> vod_adsVod = getAdInfo(MyApplication.getMAC(), Ad.VOD, 2);
						if(vod_adsVod != null){
							vod_adsList.addAll(vod_adsVod);
						}
						if(!vod_adsList.isEmpty()){
							adVod.setDetails(vod_adsList);
							AdData.create(adVod);
							
							for(AdDetail adl : AdData.getVod().getDetails()){
								Log.i("cloud_ad", "云广告数据同步,广告名称->" + adl.getName());
								AsyncImageTask task = new AsyncImageTask(adl);
						        task.execute();
							}
						}
						
						//电视广告
						Ad adTv = new Ad();
						adTv.setType(Ad.TV);
						List<AdDetail> tv_adsList = new Vector<AdDetail>();
						tv_adsList.clear();
						
						List<AdDetail> tv_adsPic = getAdInfo(MyApplication.getMAC(), Ad.TV, 1);
						if(tv_adsPic != null){
							tv_adsList.addAll(tv_adsPic);
						}
						
						List<AdDetail> tv_adsvod = getAdInfo(MyApplication.getMAC(), Ad.TV, 2);
						if(tv_adsvod != null){
							tv_adsList.addAll(tv_adsvod);
						}
						
						if(!tv_adsList.isEmpty()){
							adTv.setDetails(tv_adsList);
							AdData.create(adTv);
							
//							Log.i("cloud-getad", tv_adsPic.get(0).getPath());
							
							for(AdDetail adl : AdData.getTv().getDetails()){
								Log.i("cloud_ad", "云广告数据同步,广告名称->" + adl.getName());
								//请求后台下载
								AsyncImageTask task = new AsyncImageTask(adl);
						        task.execute();
							}
						}
						
						//不断请求后台是否下载好了广告,全部下载完成就退出
						Looper.loop();
					}
				}.start();
			}
		} else {
			Log.i("cloud_ad", "广告授权:" + MyApplication.adEnable + ",cloudOnline:" + myCloudOnline);
		}
	}
	

	//	通过代理服务器下载云端的广告文件,返回本地文件的路径
	//	filePathName 广告在云端的相对路径
	//	adName 这个广告的名称，用于上传日志
	private String downloadFileProxy(String filePathName, String adName){
		String urlDownload = Constants.DEFAULT_CLOUD_SERVER + "upload/" + filePathName;
		String localFilePath = "";
		boolean download = false;
		boolean sizeVaild = false;//文件大小是否合法
		
		String hostAdFilePath = "";//文件名，包括路径
		
		if(FileUtils.getFileName(filePathName, true) != null){
			hostAdFilePath = MyApplication.hostMyResUrl + FileUtils.getFileName(filePathName, true);
			

			Log.i("cloud-download",adName + "->>" + "网络文件路径:" + urlDownload);
			Log.i("cloud-download",adName + "->>" + "本地服务器文件路径:" + hostAdFilePath);
			Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(httpProxy, httpProxyPort));
			try {
				/************判断文件是否需要下载**************/
				URL url = new URL(urlDownload);
				URLConnection con = url.openConnection(proxy);
				
				//判断文件长度是否合法
				int contentLength = con.getContentLength();
//				Log.i("cloud-download",adName + "->>" + "长度 :"+contentLength);
				
				if(filePathName.contains(".jpg") || filePathName.contains(".bmp")){
					if(contentLength <= 1024 * 1024){
//						Log.i("cloud-download",adName + "->>" + "图片长度符合1024K大小要求");
						sizeVaild = true;
					}else{
						Log.e("cloud-download",adName + "->>" + "图片超过1M大小要求了，拒绝下载.");
						download = false;
					}
				}
				
				if(filePathName.contains(".mp4")){
					if(contentLength <= 20 * 1024 * 1024){
//						Log.i("cloud-download",adName + "->>" + "视频长度符合20M大小要求");
						sizeVaild = true;
					}else{
						Log.e("cloud-download",adName + "->>" + "视频超过20M大小要求了，拒绝下载.");
						download = false;
					}
				}
				
				//查询服务器是否存在文件
				if(sizeVaild){
					try {
						String url1 = MyApplication.getHost() + SPAService.PROJECT + "/api/exist-myres.json?filename=" + FileUtils.getFileName(filePathName, true);
						String result1 = HttpHelper.getStringSync(null, url1);

						Log.i("cloud-download", adName + "->>" + "exist-myres result1 =" + result1);

						if (result1 != null){
							ModelBean d = gson.fromJson(result1, ModelBean.class);
							if (d != null) {
								if (!d.getCode().equals(-1) && d.getData() != null){
									if(d.getData().equals("Y")){
										//存在
										download = false;
										//存在就直接赋值过去
										localFilePath = hostAdFilePath;
										Log.w("cloud-download", adName + "->>已下载到服务器，不需要再下载.");
									}else if(d.getData().equals("N")){
										//不存在
										download = true;
										Log.e("cloud-download", adName + "->>服务器没有缓冲，下载之....");
									}
								}else{
									
								}
							}
						}
					} catch (HttpRequestFailException e) {
						Log.e("cloud-download", adName + "->>" + "exist-myres.json请求失败:" + e.getMessage());
						//失败了，就当作是没有的，重新下载一次，服务器会判断的，已经下载就会返回文件路径
						download = true;
					}
					
					//	download == true 需要服务器下载
					if(download){
						try {
							Log.i("cloud-download",adName + "->>" + "提交请求让本地服务器下载文件中..."); 
							EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_AD_DOWNLOADING + adName));
							
							String url1 = MyApplication.getHost() + SPAService.PROJECT + "/api/httpdownload-myres.json?url=" 
											+ urlDownload + "&mustdown=true";
							long downloadBeginTime = System.currentTimeMillis();
							String result1 = HttpHelper.getStringSync(null, url1,10 * 60 * 1000);//等待下载10分钟
//							Log.i("cloud-download", adName + "->>" + "httpdownload-myres result1 =" + result1);
							if (result1 != null){
								ModelBean d = gson.fromJson(result1, ModelBean.class);
/*								{"code":200,"msg":"成功！","data":"http://172.16.1.202:8081/upload/myres/aaa.mp4"}
								{"code":-1,"msg":"失败！","data":""}
								{"code":-2,"msg":"已下载！","data":"http://172.16.1.202:8081/upload/myres/aaaee.mp4"}
								{"code":-3,"msg":"没有指定需要下载的URL！","data":""}*/
								if (d != null) {
									if (d.getCode().equals(200) || d.getCode().equals(-2)){
										Log.i("cloud-download",adName + "->>" + "下载结束," + d.getMsg()); 
										localFilePath = hostAdFilePath;
										long downloadTime  = System.currentTimeMillis() - downloadBeginTime;
										EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_AD_DOWNLOAD_FINISH 
												+ adName 
												+ "\t" + contentLength/1024 + "K"
												+ "\t" + downloadTime + "ms"));
									}else{
										localFilePath = "";
									}
								}else{
									Log.i("cloud-download", adName + "->>" + "Json解析出错");
								}
							}
						} catch (HttpRequestFailException e) {
							Log.e("cloud-download", adName + "->>" + "httpdownload-myres.json请求失败:" + e.getMessage());
							//失败了，就当作是没有的，重新下载一次，服务器会判断的，已经下载就会返回文件路径
							download = true;
						}
					}else{
						EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_AD_DOWNLOAD_NO_NEED + adName));
						localFilePath = hostAdFilePath;
					}
				}else{
					localFilePath = "";
					EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_AD_DOWNLOAD_SIZE_INVAILD + adName));
				}
			} catch (Exception e) {
				Log.i("cloud-download",adName + "->>" + "网络下载文件失败。");
				e.printStackTrace();
				EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_AD_DOWNLOAD_FAIL + adName));
				localFilePath = "";
			}
		}else{
			Log.e("cloud-download",adName + "->>" + "错误的路径或者文件名，无法下载"); 
		}
		
		return localFilePath;
	}
	
	public class AsyncImageTask extends AsyncTask<Void, Integer, String> {
		AdDetail add; 
        public AsyncImageTask(AdDetail add) {
        	this.add = add;
        }
 
        // 后台运行的子线程子线程
        @Override
        protected String doInBackground(Void... params) {
            try {
            	String localPath = downloadFileProxy(add.getPath(),add.getName());
            	
            	if(!localPath.equals("")){  
            		Log.i("cloud-download","服务器文件路径=" + localPath);
	            	add.isCache = true;
	            	add.localPath = localPath;
            	}
            	
                return localPath;
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
 
        // 这个放在在ui线程中执行
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        }
    }
	
	private String downloadApkFileProxy(String filePathName, String adName){
		String urlDownload = filePathName;
		String localFilePath = "";
		boolean download = false;
		boolean sizeVaild = false;//文件大小是否合法
		
		String hostAdFilePath = "";//文件名，包括路径
		
		if(FileUtils.getFileName(filePathName, true) != null){
			hostAdFilePath = MyApplication.hostMyResUrl + FileUtils.getFileName(filePathName, true);
			

			Log.i("cloud-download",adName + "->>" + "网络文件路径:" + urlDownload);
			Log.i("cloud-download",adName + "->>" + "本地服务器文件路径:" + hostAdFilePath);
			Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(httpProxy, httpProxyPort));
			try {
				/************判断文件是否需要下载**************/
				URL url = new URL(urlDownload);
				URLConnection con = url.openConnection(proxy);
				
				//判断文件长度是否合法
				int contentLength = con.getContentLength();
//				Log.i("cloud-download",adName + "->>" + "长度 :"+contentLength);

				if(filePathName.contains(".apk")){
					if(contentLength <= 50 * 1024 * 1024){
//						Log.i("cloud-download",adName + "->>" + "视频长度符合20M大小要求");
						sizeVaild = true;
					}else{
						Log.e("cloud-download",adName + "->>" + "视频超过50M大小要求了，拒绝下载");
						download = false;
					}
				}
				
				//查询服务器是否存在文件
				if(sizeVaild){
					try {
						String url1 = MyApplication.getHost() + SPAService.PROJECT + "/api/exist-myres.json?filename=" + FileUtils.getFileName(filePathName, true);
						String result1 = HttpHelper.getStringSync(null, url1);

						Log.i("cloud-download", adName + "->>" + "exist-myres result1 =" + result1);

						if (result1 != null){
							ModelBean d = gson.fromJson(result1, ModelBean.class);
							if (d != null) {
								if (!d.getCode().equals(-1) && d.getData() != null){
									if(d.getData().equals("Y")){
										//存在
										download = false;
									}else if(d.getData().equals("N")){
										//不存在
										download = true;
									}
								}else{
									
								}
							}
						}
					} catch (HttpRequestFailException e) {
						Log.e("cloud-download", adName + "->>" + "exist-myres.json请求失败:" + e.getMessage());
						//失败了，就当作是没有的，重新下载一次，服务器会判断的，已经下载就会返回文件路径
						download = true;
					}
					
					//	download == true 需要服务器下载
					if(download){
						try {
							Log.i("cloud-download",adName + "->>" + "提交请求让本地服务器下载文件中..."); 
							
							String url1 = MyApplication.getHost() + SPAService.PROJECT + "/api/httpdownload-myres.json?url=" 
											+ urlDownload + "&mustdown=true";
							long downloadBeginTime = System.currentTimeMillis();
							String result1 = HttpHelper.getStringSync(null, url1,10 * 60 * 1000);//等待下载10分钟
//							Log.i("cloud-download", adName + "->>" + "httpdownload-myres result1 =" + result1);
							if (result1 != null){
								ModelBean d = gson.fromJson(result1, ModelBean.class);
/*								{"code":200,"msg":"成功！","data":"http://172.16.1.202:8081/upload/myres/aaa.mp4"}
								{"code":-1,"msg":"失败！","data":""}
								{"code":-2,"msg":"已下载！","data":"http://172.16.1.202:8081/upload/myres/aaaee.mp4"}
								{"code":-3,"msg":"没有指定需要下载的URL！","data":""}*/
								if (d != null) {
									if (d.getCode().equals(200) || d.getCode().equals(-2)){
										localFilePath = hostAdFilePath;
										long downloadTime  = System.currentTimeMillis() - downloadBeginTime;
										Log.i("cloud-download",adName + "->>" + "下载结束," + d.getMsg() + contentLength/1024 + "K"
												+ " " + downloadTime + "ms"); 
									}else{
										localFilePath = "";
									}
								}else{
									Log.i("cloud-download", adName + "->>" + "Json解析出错");
								}
							}
						} catch (HttpRequestFailException e) {
							Log.e("cloud-download", adName + "->>" + "httpdownload-myres.json请求失败:" + e.getMessage());
							//失败了，就当作是没有的，重新下载一次，服务器会判断的，已经下载就会返回文件路径
							download = true;
						}
					}else{
						localFilePath = hostAdFilePath;
					}
				}else{
					localFilePath = "";
				}
			} catch (Exception e) {
				Log.i("cloud-download",adName + "->>" + "网络下载文件失败。");
				e.printStackTrace();
				localFilePath = "";
			}
		}else{
			Log.e("cloud-download",adName + "->>" + "错误的路径或者文件名，无法下载"); 
		}
		
		return localFilePath;
	}
	
	public static String getUpdateInfo(String mac) {
		// Log.i("ad", "广告数据...");
		String url = null;
		if(MyApplication.shareUid != null && MyApplication.shareUid.equals("android.uid.system")){
			url = Constants.DEFAULT_CLOUD_CTRL + "/myapk?name=spa" + "&type=root&auth=" + MyApplication.authToCompany;
		}else{
			url = Constants.DEFAULT_CLOUD_CTRL + "/myapk?name=spa" + "&type=noroot&auth=" + MyApplication.authToCompany;
		}
		
		try {
			String result = HttpHelper.myGetStringSync(null, url, isNeedhttpProxy);
			Log.e("cloud-update", "result=" + result);
			if (result != null && !result.equals("ERROR, NO_FILE") && !result.equals("ERROR, UPDATE_SHUTDOWN")){
			
				JSONObject jo = new JSONObject(result);
				String version = jo.getString("version");
				String path = jo.getString("url");
				Log.i("cloud-update", version + "->>" + path);
				
				int version1 = AppUtil.getVersion(MyApplication.getContext(), MyApplication.getContext().getPackageName());//版本号
				String versionName = AppUtil.getVersionName(MyApplication.getContext(), MyApplication.getContext().getPackageName());//主版本号
				Log.i("cloud_update", "当前版本:" + versionName + "." +version1);
				
				String v[] = version.split("\\.");
				Log.i("cloud-update", "cloud apk version:" + v[2]);
				if(v.length == 3 && Integer.parseInt(v[2]) > version1){
					return path;
				} else {
					return null;
				}
			}
			return null;
		} catch (Throwable e) {
			Log.e("cloud-update", "升级数据获取失败:" + e.getMessage());
			e.printStackTrace();

		}
		return null;
	}
	private void updateApkFromCloud() {
		if (myCloudOnline) {
			String enable = SysConf.extendConfGetValue(SysConf.SYS_CONF_CLOUD_APK_UPDATE_ENABLE, "1");
			Log.i("cloud-update", "云端SPA升级，状态：" + enable);
			if (enable.equals("1")) {
				
				new Thread() {
					@Override
					public void run() {
						Looper.prepare();
						//电影广告
						
						String path = getUpdateInfo(MyApplication.getMAC());
						if(path != null && !MyApplication.localUpdatting){
							//路径不为空，而且没有通过本地的升级机制升级
							String localePath = downloadApkFileProxy(path, "SPA");//SPA只是为了日志显示
							if(!localePath.equals("")){
								//准备更新吧
								Log.i("cloud-update", "updateReceiver..准备更新..");
								Message msg = new Message();
								Bundle data = new Bundle();
								data.putString("path", localePath);
								msg.what = CLOUD_UPDATE_SPA;
								msg.setData(data);

								handlerMsg.sendMessage(msg);
							}
						}
						
						//不断请求后台是否下载好了广告,全部下载完成就退出
						Looper.loop();
					}
				}.start();
			}
		}
	}	
	private void adShowFinish(final int id) {
		new Thread() {
			@Override
			public void run() {
				try {
					String url = cloud_url + "/api/ad-show-time.json?mac=" + MyApplication.getMAC() + "&id=" + id;
					String result = HttpHelper.myGetStringSync(null, url, isNeedhttpProxy);
					ModelBean d = gson.fromJson(result, ModelBean.class);
					if (d.getCode().equals(200)) {
						Log.i("ad","上报广告播放次数->>" + result);
					} else {
						Log.i("ad","上报广告播放次数失败"); 
					}
				} catch (HttpRequestFailException e) {
					Log.e("ad", e.getMessage());
				}
			}
		}.start();
	}

	public static void requestRpcUdp(final String sockid, final String request,	final String startTag, final String endTag, final String errorStartTag, final String type) {
		new Thread() {
			public void run() {
				String IP = "";
				String PORT = "";
				
				if(type.endsWith("locale")){
					//本地服务器请求
					String info[] = MyApplication.getHostIpAndPort().split(":");
					if(info.length == 2){
						IP = info[0];
						PORT = info[1];
					}
				} else if(type.endsWith("interface")){
					//策成，捷信达等管理系统接口请求
					IP = MyApplication.interfaceServerIp;
					PORT = MyApplication.interfaceServerPort;
				}
				
				Log.i("rpc-udp", IP + "," + PORT + "," + request + "," + startTag + "," + endTag);
				if(IP.equals("") || PORT.equals("")){
					Log.e("rpc-udp", "无效IP或PORT," + IP + "," + PORT);
					return;
				}
				
				UdpCallback c = new UdpCallback() {
					@Override
					public void receive(String s) {
						//返回的数据需要去掉\r\n,\n这些字符，否则会影响数据的处理
						Log.i("rpc-udp", "本地调用成功->" + s);
						replyRpc(sockid,s.replace("\r\n", "").replace("'", "’"));
					}
				};
				try {
					int p = Integer.parseInt(PORT);
					new UdpClient(IP, p, c, startTag, endTag, errorStartTag).send(request);
				} catch (NumberFormatException n) {
					Log.i("rpc-udp", "转换出错");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
	}
	
	public static void requestRpcHttp(final String sockid, final String connent, final String type) {

		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				String url = "";
				String c = connent;

				if(type.endsWith("locale")){
					//本地服务器请求
					if(!c.contains("?")){
						c += "?mac=" + MyApplication.getMAC();
					} else {
						c += "&mac=" + MyApplication.getMAC();
					}
					
					url = MyApplication.getHost() + SPAService.PROJECT + "/" + c; 
				} else if(type.endsWith("interface")){
					//策成，捷信达等管理系统接口请求
					url = "http://" + MyApplication.interfaceServerIp + ":" + MyApplication.interfaceServerPort + "/" + c; 
					Log.i("rpc-http","本地调用接口url->" + url);
				}
				
				HttpHelper.myGetStringAsync(MyApplication.getContext(), url, null, new AsyncHttpResponseHandler() {
					
					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						// TODO Auto-generated method stub
						Log.i("rpc-http","本地调用成功->" + new String(arg2));
		            	replyRpc(sockid,new String(arg2));
					}
					
					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
						// TODO Auto-generated method stub
						Log.i("rpc-http", "本地调用失败." + arg3.getMessage()); 
					}
				}, isNeedhttpProxy);
				Looper.loop();
			}
		}.start();
	}

	public static void replyRpc(final String sockid, final String connent) {

		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				
				try {
					//超过1000字节的数据，就要分包，重组是在云端
					if(connent.length() > 1000){
						String msgSendNext = connent;
						for(int i = connent.length();i > 0;i = i-999){
							Log.i("rpc", "数据长度->>" + msgSendNext.length());
							String url = "http://" + cloudLogsServerIp + ":"+ cloudLogsServerPort + "/sock-write?id=" + sockid + "&msg=";
							if(i > 1000){
								Log.i("rpc", "发送内容->>" + msgSendNext.subSequence(0, 999).toString());
								url += URLEncoder.encode(msgSendNext.subSequence(0, 999).toString(), "UTF-8");
								url += "&cache=true";//表示分包
								msgSendNext = msgSendNext.substring(999);//下一次要发送的
							}else{
								Log.i("rpc", "发送内容->>" + msgSendNext);
								url += URLEncoder.encode(msgSendNext, "UTF-8");
	//							Log.i("rpc", "发送内容->>" + connent);
								Log.i("rpc", "发送完成,总共字节数" + connent.length());
							}
							
							String rv = HttpHelper.myGetStringSync(MyApplication.getContext(), url, isNeedhttpProxy);
							Log.i("rpc","远程过程调用->" + rv);
						}
					}else{
						String url = "http://" + cloudLogsServerIp + ":"+ cloudLogsServerPort + "/sock-write?id=" + sockid + "&msg=";
						url += URLEncoder.encode(connent, "UTF-8");
	//					Log.i("rpc", "发送->>" + url);
						String rv = HttpHelper.myGetStringSync(MyApplication.getContext(), url, isNeedhttpProxy);
						Log.i("rpc","远程过程调用->" + rv);
					}
				} catch (HttpRequestFailException | UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Looper.loop();
			}
		}.start();
	}

	private void getSecLogKey() {
		new Thread() {
			@Override
			public void run() {
				try {
//					String url = Constants.DEFAULT_CLOUD_LOGS_SERVER + "/seckey";
					String url = "http://" + cloudLogsServerIp + ":"+ cloudLogsServerPort  + "/seckey";
//					Log.i("logs","getSecLogKey url->>" + url);
					String result = HttpHelper.myGetStringSync(null, url, isNeedhttpProxy);
					
					if (result != null) {
//						Log.i("logs","seckey->>" + result);
						try{
							for(int i=0;i<secKeyPosition.length;i++){
								secKey += result.charAt(secKeyPosition[i]);
							}
							Log.i("logs","密码获取成功");
						}catch(Exception e){
							Log.i("logs","密码获取失败！");
						}
						
					} else {
						Log.i("logs","seckey获取失败"); 
					}
				} catch (HttpRequestFailException e) {
					Log.e("ad", e.getMessage());
				}
			}
		}.start();
	}

	private void initUpdateLog() {
		final AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				Log.i("logs", "日志处理完成:" + new String(arg2));
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				Log.i("logs", "日志处理失败.");
			}
		};
		
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				String content;

				if(secKey.equals("")){
					getSecLogKey();
				}else{
					if(myCloudOnline && !httpProxy.equals("") && httpProxyPort != 0 && cloudLogsEnable){
						try {
							content = null;
							//取出一个要发的记录
							while(decLogsList.size() > 0){
								synchronized(decLogsList) {
									if(!decLogsList.isEmpty()) {
										content = decLogsList.poll();
									}
								}
								if(content != null){
									//content = "\t" + 123 + "\t" + 456;
									//加密一下日志
									int count = 0;
									int index = 0;
									while((index=content.indexOf("\t",index)) != -1){
							            index = index + "\t".length();
							            count++;
							        }
									
									String str = count + content;
									
//										Log.i("logs", "日志包含  t " + count + "个");	
//										Log.i("logs", "发送日志:" + content);		
									
									int len = str.getBytes().length;
									
									if(len%8 != 0){
//											Log.i("logs", "长度:" + len + ",需要补空格"+ (8-len%8) + "个");	
										for(int j=0; j < 8- len%8; j++){
											str += " ";
										}
									}
//										Log.i("logs", "长度:" + str.getBytes().length);	
									
									String decContent = DesCryptoUtil.encode(DesCryptoUtil.desCrypto(str.getBytes(),secKey));
//										String url = Constants.DEFAULT_CLOUD_LOGS_SERVER + "/seclog?content=" + decContent;
									String url = "http://" + cloudLogsServerIp + ":"+ cloudLogsServerPort + "/seclog?content=" + decContent;
									HttpHelper.myGetStringAsync(getBaseContext(), url, null, handler,isNeedhttpProxy);
								}else{
									Log.i("logs", "没有日志要发送");
								}
								
								try {
									Thread.sleep(100);
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
							}
							
							while(logsList.size() > 0){
								synchronized(logsList) {
									if(!logsList.isEmpty()) {
										content = logsList.poll();
									}
								}
								if(content != null){
									//content = "\t" + 123 + "\t" + 456;
//										Log.i("logs", "发送普通日志:" + content);
//										String url = Constants.DEFAULT_CLOUD_LOGS_SERVER + "/log?content=" + content;
									String url = "http://" + cloudLogsServerIp + ":"+ cloudLogsServerPort + "/log?content=" + content;
									HttpHelper.myGetStringAsync(getBaseContext(), url, null, handler,isNeedhttpProxy);
								}else{
									Log.i("logs", "没有日志要发送");
								}
								
								try {
									Thread.sleep(100);
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
							Log.e("logs", "SPAService.initUpdateLog:" + e.getMessage());
						}
					}else{
//						Log.i("logs", "可能不能正常联网，不能发送日志->>" + myCloudOnline + ":" + httpProxy + ":" + httpProxyPort + ":" + cloudLogsEnable);
					}
					
				}

			}
		}; 
		
/*		if(cloud_log_timer == null){
			cloud_log_timer = new Timer(true);
			cloud_log_timer.schedule(task, 1000, 2 * 1000);
		}*/
		
		cloudThreadPool.scheduleAtFixedRate(task, 1000, 2 * 1000, TimeUnit.MILLISECONDS);
	}
	
	/* 广告播放完毕事件接口 */
	public void onEventMainThread(CloudAdShowFinishEvent event) {
		adShowFinish(event.getId());
		initAd();
	}

	//云端日志
	public void onEventMainThread(SendLogEvent event) {
		try{
			if(decLogsList != null && event.msg != null  && event.noDec == false){
				String content = "\t" + DateUtils.formatToLong(new Date()) + "\t"  + app.getAuthToCompany() 
						+ "\t" + MyApplication.getMAC() + "\t" + MyApplication.getDeviceInfo().getCategoryName() 
						+ "-" +MyApplication.getDeviceInfo().getName()+ "\t" + event.msg;
				decLogsList.offer(content);
			}else if(logsList != null && event.msg != null  && event.noDec == true){
				String content = DateUtils.formatToLong(new Date()) + "%09"  + app.getAuthToCompany() 
						+ "%09" + MyApplication.getMAC() + "%09" + MyApplication.getDeviceInfo().getCategoryName() 
						+ "-" +MyApplication.getDeviceInfo().getName()+ "%09" + event.msg;
				logsList.offer(content);
			}
		}catch(Exception e){
			
			if(MyApplication.getDeviceInfo() == null)
				Log.i("logs", "发送日志出错:" + e.getMessage());
		}
	}
	
	public void sendStratUpLog(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				boolean flag = true;
				// TODO Auto-generated method stub
				while(flag)
				if(MyApplication.getApkVersion() != null
						&& Constants.API_VERSION != null
						&& Constants.LYAGENT_VERSION != null
						&& MyApplication.serverVersion != null
						&& MyApplication.fullDeviceInfo != null){
					
						EventBus.getDefault().post(new SendLogEvent(
										MyLogsManager.CLOUD_LOGS_SYSTEM_STARTUP
												+ "\t"
												+ MyApplication.getApkVersion()
												+ "\t"
												+ Constants.API_VERSION
												+ "\t"
												+ Constants.LYAGENT_VERSION
												+ "\t"
												+ MyApplication.serverVersion
												+ "\t"
												+ MyApplication.fullDeviceInfo
														.getCreateTime()));
						Log.i("init", MyLogsManager.CLOUD_LOGS_SYSTEM_STARTUP
												+ "\t"
												+ MyApplication.getApkVersion()
												+ "\t"
												+ Constants.API_VERSION
												+ "\t"
												+ Constants.LYAGENT_VERSION
												+ "\t"
												+ MyApplication.serverVersion
												+ "\t"
												+ MyApplication.fullDeviceInfo
														.getCreateTime());
						HashMap<String, String> lang = new HashMap<String, String>();
						lang.put("zh_CN", 	"简体中文");
						lang.put("zh_TW",   "繁体中文");
						lang.put("en", 		"英文");
						EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_SYSTEM_LANGUAGE + lang.get(MyApplication.currectLocale.toString())));
						flag = false;
				}
				
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	public void initSocket(){
		
		new Thread() {
			@Override
			public void run() {
				SocketClient socketClient = new SocketClient(null, getBaseContext());
				socketClient.start();

				//初始化二维码浮窗
				Intent qrFx = new Intent(getApplicationContext(), QRFloatWin.class);
				startService(qrFx);
			}
		}.start();
	}
	
	
	private void checkSpaUpdateHistory() {
		// 上报IP
		new Thread() {
			@Override
			public void run() {

				String lastSpaVersion = SharedPreferencesConfig.getLastSpaVersion(MyApplication.getContext());
				if(!lastSpaVersion.equals("")){
					if(!lastSpaVersion.equals(MyApplication.spaVersion)){
						Log.i("cloud-update", "升级成功" + MyApplication.authToCompany  + ","+ MyApplication.getMAC() + "," + MyApplication.getDeviceInfo()
								.getCategoryName() + "-" + MyApplication.getDeviceInfo().getName() + ","+"升级成功,"+lastSpaVersion + "," + MyApplication.spaVersion);
						//版本不一样，表示存在一次升级成功，发送日志吧
						EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_UPDATE_FINSH + lastSpaVersion + "\t" + MyApplication.spaVersion));
						//只有发送成功才更新
						
						String url = Constants.DEFAULT_CLOUD_CTRL + "/myapklogwrite?content=" + MyApplication.authToCompany  + ","+ MyApplication.getMAC() + "," + MyApplication.getDeviceInfo()
								.getCategoryName() + "-" + MyApplication.getDeviceInfo().getName() + ","+"升级成功,"+lastSpaVersion + "," + MyApplication.spaVersion;
						try {
							HttpHelper.myGetStringSync(null, url, isNeedhttpProxy);
						} catch (HttpRequestFailException e) {
							// TODO Auto-generated catch block
							e.printStackTrace(); 
						}
						
						SharedPreferencesConfig.setLastSpaVersion(MyApplication.getContext(), MyApplication.spaVersion);
					}
				} else {
					SharedPreferencesConfig.setLastSpaVersion(MyApplication.getContext(), MyApplication.spaVersion);
				}
				
			}
		}.start();
	}

	private void initReportSocketId(final String socketId) {
		// 上报IP
		new Thread() {
			@Override
			public void run() {

				String url = Constants.DEFAULT_CLOUD_SERVER + "/api/online.json?mac=" + MyApplication.getMAC() + "&crop=" 
							+ MyApplication.authToCompany  + "&sockid=" + socketId;
				Log.i("socket", "请求online：" + url);
				String result = null;
				try {
					result = HttpHelper.myGetStringSync(null, url, isNeedhttpProxy);
				} catch (HttpRequestFailException e) {
					// TODO Auto-generated catch block
					e.printStackTrace(); 
				}
				Log.i("socket", "上报socket id 到云服务器：" + result);
				
				try { 
					String url1 = "http://" + cloudLogsServerIp + ":"+ cloudLogsServerPort + "/sock-info?id=" + 
							socketId + "&info=" + "SMARTTV" + "_" + MyApplication.authToCompany + "_" + MyApplication.getMAC() +
							"_" + MyApplication.getDeviceInfo().getCategoryName() 
							+ "_" +MyApplication.getDeviceInfo().getName() + "&timestamp=server";
					String result1 = null;
					Log.i("socket", "url1：" + url1);
					result1 = HttpHelper.myGetStringSync(null, url1, isNeedhttpProxy);
					Log.i("socket", "修改云端sock描述信息：" + result1);
				} catch (HttpRequestFailException e) {
					// TODO Auto-generated catch block
					e.printStackTrace(); 
				}
			}
		}.start();
	}
	
	/* 初始化类型列表时使用这个 */
	public void onEventMainThread(CloudSocketIdReportEvent event) {
		Log.d("SPABackService", "onEventMainThread-->" + "获取视频类别");
		// 点播
		initReportSocketId(event.id);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		/*if(heartbeat_timer != null) {
			heartbeat_timer.cancel();
			heartbeat_timer = null;
		}*/
		
/*		if(alive_timer != null){
			alive_timer.cancel();
			alive_timer = null;
		}*/
		
		/*if(cloud_log_timer != null){
			cloud_log_timer.cancel();
			cloud_log_timer = null;
		}*/
	}

	private static class ThisHandler extends Handler {
		private WeakReference<MyCloudBackService> wrActivity;

		public ThisHandler(MyCloudBackService activity) {
			wrActivity = new WeakReference<MyCloudBackService>(activity);
		}

		@Override
		public void handleMessage(Message message) {
			MyCloudBackService act = wrActivity.get();
			switch(message.what){

				case CLOUD_INIT:
					act.initCloudServer();				
					break;
				
				case CLOUD_LOGIN:
//					act.initlogin();				//登陆完成后，会发出CLOUD_GET_DATA的消息
					sendEmptyMessageDelayed(CLOUD_GET_DATA, 100);
					break;
					
				case CLOUD_GET_DATA:
					act.initHeartbeat();			// 初始化心跳
					act.initAd();					// 初始化广告
					act.initUpdateLog();
					act.sendStratUpLog();			// 发送启动完成日志到云端
					act.updateApkFromCloud();		// 通过云端升级
					act.checkSpaUpdateHistory();	// 检测这次启动和上一次启动的版本是不是一致的，不一致表明成功升级了
					
					String rootVersion = AppUtil.getVersionName(act, act.getPackageName());//主版本号 1.x,2.x,3.x等等格式
					if(rootVersion != null && !rootVersion.startsWith("3.")){
						if(SysConf.extendConfGetValue(SysConf.SYS_CONF_WEB_APP_INF_ENABLE,"0").equals("1")){
							act.initSocket();				//用来实现手机遥控
						}
					}
					if(SharedPreferencesConfig.getDebug(act).equals(SharedPreferencesConfig.DEBUG_ON)){
						//放那些需要调试的功能
					}
					break;	
					
				case CLOUD_UPDATE_SPA://升级
					// 有更新直接安装之
					Log.i("cloud", "下载路径:" + message.getData().getString("path"));
					new WebInstaller(MyApplication.getContext(), message.getData().getString("path"), true).downloadAndInstall();
					break;					
			}
		}
	}

}
